import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class WebViewWidget extends StatefulWidget {
  final String url;
  final String? title;
  final bool showAppbar;
  final bool titleChange;
  const WebViewWidget({super.key,required this.url,this.title,this.showAppbar = true,this.titleChange = true});
  @override
  State<WebViewWidget> createState() => _WebViewWidgetState();
}

class _WebViewWidgetState extends State<WebViewWidget> {
  late InAppWebViewController controller;
  String? _title = "";
  bool isShowAppbar = false;
  @override
  void initState() {
    isShowAppbar = widget.title == null ? true:false;
    _title = widget.title ?? "";
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: widget.showAppbar  ? AppBar(title: Text(!widget.titleChange ? (widget.title ?? "") : (_title ?? "")),) : null,
      body: InAppWebView(
        initialSettings:InAppWebViewSettings(supportZoom: false,cacheEnabled: false),
        initialUrlRequest:
        URLRequest(url: WebUri.uri(Uri.parse(widget.url))),
        onWebViewCreated: (controller) {
          this.controller = controller;
          controller.evaluateJavascript(source: """document.body.style.fontSize = '20px';""");
        },
        onConsoleMessage: (controller, consoleMessage) {
          debugPrint("web日志：${consoleMessage.toString()}");
        },
        onLoadStart: (controller,url){
          debugPrint("loadStartUrl ==$url");
        },
        onTitleChanged: (controler,title){
          setState(() {
            _title = title;
          });
        },
        shouldOverrideUrlLoading: (controller, navigationAction)async{
          var url = navigationAction.request.url;
          debugPrint("webUri == $url");
          return NavigationActionPolicy.ALLOW;
        },
      ),
    );
  }
}
